import axios from '@/libs/api.request'
import Qs from 'qs'
import { getLocalStorageToken } from '@/libs/util'
import * as auth from '@/api/auth'
import * as ResponseStatus from '@/api/response-status'
import fileDownload from 'js-file-download'
export const SYS_INFO_KEY = 'sysInfo'
export const localStorage = window.localStorage
/**
 * 根据指定的modal名打开模态框
 * @param self this
 * @param modal modal名
 */
export const showModal = (self, modal) => {
  self.modal[modal] = true
}

/**
 * 根据指定的modal名关闭模态框
 * @param self this
 * @param modal modal名
 */
export const cancelModal = (self, modal) => {
  self.modal[modal] = false
}

/**
 * 重置表单
 * @param self this
 * @param formRef form ref名称
 */
export const resetForm = (self, formRef) => {
  self.$refs[formRef].resetFields()
}

/**
 * post请求，application/json
 * @param {*} url 请求url
 * @param {*} data json对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                          'Authorization': 'Bearer ' + getLocalStorageToken()
                        }
                      如果不需要传递headers，则直接使用{}
 */
export const doPostJson = (url, data, headers) => {
  headers['Authorization'] = 'Bearer ' + getLocalStorageToken()
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url
    let timestamp = new Date().getTime()
    let nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignJson(url, timestamp, nonceStr, data)
  }
  return axios.request({
    url: url,
    method: 'POST',
    data: data,
    headers: headers
  })
}

/**
 * post请求，application/x-www-form-urlencoded
 * @param {*} url 请求url
 * @param {*} data json对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                          'Authorization': 'Bearer ' + getLocalStorageToken()
                        }
                      如果不需要传递headers，则直接使用{}
 */
export const doPostQs = (url, data, headers) => {
  headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  headers['Authorization'] = 'Bearer ' + getLocalStorageToken()
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url
    let timestamp = new Date().getTime()
    let nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignQs(url, timestamp, nonceStr, data)
  }
  return axios.request({
    url: url,
    method: 'POST',
    data: Qs.stringify(data, {arrayFormat: 'repeat'}),
    headers: headers
  })
}

/**
 * post请求，application/x-www-form-urlencoded，返回arraybuffer数据，如图片
 * @param {*} url 请求url
 * @param {*} data json对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                          'Authorization': 'Bearer ' + getLocalStorageToken()
                        }
                      如果不需要传递headers，则直接使用{}
 */
export const doPostQsArrayBuffer = (url, data, headers) => {
  headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  headers['Authorization'] = 'Bearer ' + getLocalStorageToken()
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url
    let timestamp = new Date().getTime()
    let nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignQs(url, timestamp, nonceStr, data)
  }
  return axios.request({
    url: url,
    method: 'POST',
    data: Qs.stringify(data, {arrayFormat: 'repeat'}),
    headers: headers,
    responseType: "arraybuffer"
  })
}

/**
*  post请求，application/x-www-form-urlencoded，返回arraybuffer数据，如图片
* @param self this
*/
export const doPostQsBlob = (url, data, headers) => {
  headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  headers['Authorization'] = 'Bearer ' + getLocalStorageToken()
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url
    let timestamp = new Date().getTime()
    let nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignQs(url, timestamp, nonceStr, data)
  }
  return axios.request({
    url: url,
    method: 'POST',
    data: Qs.stringify(data, {arrayFormat: 'repeat'}),
    headers: headers,
    responseType: "blob"
  })
}

/**
 * get请求
 * @param {*} url 请求url，包含请求参数
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                          'Authorization': 'Bearer ' + getLocalStorageToken()
                        }
                      如果不需要传递headers，则直接使用{}
 */
export const doGet = (url, headers) => {
  headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  headers['Authorization'] = 'Bearer ' + getLocalStorageToken()
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url.indexOf('?') > 0 ? url.split('?')[0] : url
    let timestamp = new Date().getTime()
    let nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignGet(url, timestamp, nonceStr)
  }
  return axios.request({
    url: url,
    method: 'GET',
    headers: headers
  })
}

/**
 * 根据form数据对象添加数据
 * @param self 父组件页面
 */
export const add = (self) => {
  return new Promise((resolve, reject) => {
    let addEditComponent = self.$refs.addEditModal
    let addForm = addEditComponent.$refs.addForm
    addForm.validate(valid => {
      if (valid) {
        addEditComponent.loading.add = true
        doPostJson(addEditComponent.urls.addUrl, addEditComponent.form, {}).then(response => {
          addEditComponent.loading.add = false
          if (response.data.code !== ResponseStatus.OK) {
            self.$Message.error(response.data.message)
          } else {
            self.$Message.success(response.data.message)
            addForm.resetFields()
            addEditComponent.modal.add = false
            let tableComponent = self.$refs.table
            tableComponent.search()
          }
          resolve(response)
        }).catch(error => {
          console.log(error)
          addEditComponent.loading['add'] = false
          self.$Message.error('添加数据失败，稍候再试')
          reject(error)
        })
      }
    })
  })
}

/**
 * 根据form数据对象修改数据
 * @param self 父组件页面
 */
export const edit = (self) => {
  return new Promise((resolve, reject) => {
    let addEditComponent = self.$refs.addEditModal
    let editForm = addEditComponent.$refs.editForm
    editForm.validate(valid => {
      if (valid) {
        addEditComponent.loading.edit = true
        // 编辑之后都变成激活状态
        addEditComponent.form.isActive = 0
        doPostJson(addEditComponent.urls.editUrl, addEditComponent.form, {}).then(response => {
          addEditComponent.loading.edit = false
          if (response.data.code !== ResponseStatus.OK) {
            self.$Message.error(response.data.message)
          } else {
            self.$Message.success(response.data.message)
            editForm.resetFields()
            addEditComponent.modal.edit = false
            let tableComponent = self.$refs.table
            tableComponent.search()
          }
          resolve(response)
        }).catch(error => {
          addEditComponent.loading.edit = false
          console.log(error)
          self.$Message.error('修改数据失败，稍候再试')
          reject(error)
        })
      }
    })
  })
}

/**
 * 根据id删除数据
 * @param tableComponent 表格组件
 * @param row 需要删除的数据对象
 */
export const remove = (tableComponent, row) => {
  return new Promise((resolve, reject) => {
    tableComponent.$Modal.confirm({
      title: '确认删除吗？',
      content: '确认删除选择的数据吗？',
      onOk: () => {
        doGet(tableComponent.urls.removeUrl + row.id, {}).then(response => {
          if (response.data.code !== ResponseStatus.OK) {
            tableComponent.$Message.error(response.data.message)
          } else {
            tableComponent.search()
          }
          resolve(response)
        }).catch(error => {
          console.log(error)
          tableComponent.$Message.error('删除数据失败，稍候再试')
          reject(error)
        })
      },
      onCancel: () => {

      }
    })
  })
}

/**
 * 根据所选择的数据批量删除
 * @param self 父组件页面
 */
export const batchRemove = (self) => {
  return new Promise((resolve, reject) => {
    let tableComponent = self.$refs.table
    if (tableComponent.table.selections.length === 0) {
      self.$Message.warning('请选择需要批量删除的数据')
    } else {
      self.$Modal.confirm({
        title: '确认删除吗？',
        content: '确认批量删除选择的数据吗？',
        onOk: () => {
          let ids = []
          tableComponent.table.selections.forEach((row, index) => {
            ids.push(row.id)
          })
          doPostJson(self.urls.batchRemoveUrl, ids, {}).then(response => {
            if (response.data.code !== ResponseStatus.OK) {
              self.$Message.error(response.data.message)
            } else {
              self.$Message.success(response.data.message)
              tableComponent.table.selections = []
              tableComponent.search()
            }
            resolve(response)
          }).catch(error => {
            console.log(error)
            self.$Message.error('批量删除数据失败，稍候再试')
            reject(error)
          })
        },
        onCancel: () => {

        }
      })
    }
  })
}

/**
 * 激活或冻结数据
 * @param tableComponent 表格组件
 * @param row 需要激活或冻结的数据对象
 */
export const active = (tableComponent, row) => {
  return new Promise((resolve, reject) => {
    let isActive = row.isActive === 0 ? 1 : 0
    let data = {
      id: row.id,
      isActive: isActive
    } 
    doPostJson(tableComponent.urls.activeUrl, data, {}).then(response => {
      if (response.data.code !== ResponseStatus.OK) {
        tableComponent.$Message.error(response.data.message)
      } else {
        tableComponent.$Message.success(response.data.message)
      }
      tableComponent.search()
      resolve(response)
    }).catch(error => {
      console.log(error)
      self.$Message.error('激活或冻结数据失败，稍候再试')
      reject(error)
    })
  })
}

/**
 * 根据所选的项，批量激活或冻结数据
 * @param self 父组件页面
 * @param isActive 0表示需要激活，1表示需要冻结
 */
export const batchActive = (self, isActive) => {
  return new Promise((resolve, reject) => {
    let rowArray = []
    let tableComponent = self.$refs.table
    if (tableComponent.table.selections.length === 0) {
      self.$Message.warning('请选择需要批量' + (isActive === 0 ? '激活' : '冻结') + '的数据')
    } else {
      tableComponent.table.selections.forEach((row, index) => {
        if (row.isActive !== isActive) {
          rowArray.push({
            id: row.id,
            isActive: isActive
          })
        }
      })
      if (rowArray.length > 0) {
        doPostJson(self.urls.batchActiveUrl, rowArray, {}).then(response => {
          if (response.data.code !== ResponseStatus.OK) {
            self.$Message.error(response.data.message)
          } else {
            self.$Message.success(response.data.message)
            tableComponent.table.selections = []
            tableComponent.search()
          }
          resolve(response)
        }).catch(error => {
          console.log(error)
          self.$Message.error('批量激活或冻结数据失败，稍候再试')
          reject(error)
        })
      } else {
        self.$Message.warning('没有需要批量' + (isActive === 0 ? '激活' : '冻结') + '的数据')
      }
    }
  })
}

/**
 * 根据searchForm分页搜索
 * @param {*} self 父组件页面
 * @param {*} reset 是否重置分页和排序搜索条件
 * @param {*} clearOldData 是否清除被选的旧数据，用于关联数据的选择新增时
 * @param {*} idProp 指明表格的id属性
 */
export const search = (self, reset, clearOldData, idProp) => {
  return new Promise((resolve, reject) => {
    let tableComponent = self.$refs.table
    let searchComponent = self.$refs.searchModal
    doClearOldData(tableComponent, clearOldData)
    doSetSearchForm(tableComponent, searchComponent, reset)
    searchComponent.loading.search = true
    tableComponent.table.loading = true
    getDataDict(tableComponent.dataDictCodes).then(response => {
      tableComponent.dataDictItems = response
      doPostJson(tableComponent.urls.searchUrl, searchComponent.searchForm, {}).then(response => {
        if (response.data.code !== ResponseStatus.OK) {
          tableComponent.$Message.error(response.data.message)
        } else {
          tableComponent.pager.total = response.data.data.total
          tableComponent.table.tableRows = response.data.data.rows
          let id = 'id'
          if (idProp) {
            id = idProp
          }
          selectSelectedData(tableComponent, id)
          selectOldData(self, tableComponent, id)
        }
        searchComponent.loading.search = false
        tableComponent.table.loading = false
        resolve(response)
      }).catch(error => {
        console.log(error)
        searchComponent.loading.search = false
        tableComponent.table.loading = false
        tableComponent.$Message.error('加载数据失败，稍候再试')
        reject(error)
      })
    }).catch(error => {
      console.log(error)
    })
    
  })
}

const doSetSearchForm = (tableComponent, searchComponent, reset) => {
  if (reset) {
    tableComponent.pager.pageNo = 1
    tableComponent.pager.pageSize = 10
    tableComponent.searchOpts.sortColumn = null
    tableComponent.searchOpts.sortOrder = null
  }
  searchComponent.searchForm.pageNo = tableComponent.pager.pageNo
  searchComponent.searchForm.pageSize = tableComponent.pager.pageSize
  searchComponent.searchForm.sortColumn = tableComponent.searchOpts.sortColumn
  searchComponent.searchForm.sortOrder = tableComponent.searchOpts.sortOrder
}

const doClearOldData = (tableComponent, clearOldData) => {
  if (clearOldData) {
    if (tableComponent.table.selections && tableComponent.table.selections.length > 0) {
      tableComponent.table.selections = []
    } else if (tableComponent.table.currentRow) {
      tableComponent.table.currentRow = {}
    }
  }
}

// 勾选上原先被勾选的数据，如翻页时，排序时，刷新时
const selectSelectedData = (tableComponent, id) => {
  if (tableComponent.table.selections && tableComponent.table.selections.length > 0) {
    for (let selectionIndex in tableComponent.table.selections) {
      let selectionData = tableComponent.table.selections[selectionIndex]
      for (let tableRowIndex in tableComponent.table.tableRows) {
        let tableRowData = tableComponent.table.tableRows[tableRowIndex]
        if (selectionData[id] === tableRowData[id]) {
          tableRowData._checked = true
          break
        }
      }
    }
  } else if (tableComponent.table.currentRow && JSON.stringify(tableComponent.table.currentRow) !== '{}') {
    for (let tableRowIndex in tableComponent.table.tableRows) {
      let tableRowData = tableComponent.table.tableRows[tableRowIndex]
      if (tableComponent.table.currentRow[id] === tableRowData[id]) {
        tableRowData._highlight = true
        break
      }
    }
  }
}

// 如果展示原先已经被选中的数据，那么此数据不可再次被选中，设置为勾选和禁用状态
const selectOldData = (self, tableComponent, id) => {
  if (self.selectedData && self.selectedData.length > 0) {
    for (let selectedDataIndex in self.selectedData) {
        let selectedDataRow = self.selectedData[selectedDataIndex]
        for (let tableRowIndex in tableComponent.table.tableRows) {
          let tableRowData = tableComponent.table.tableRows[tableRowIndex]
          if (selectedDataRow[self.selectedDataIdProp] === tableRowData[id]) {
            tableRowData._checked = true
            tableRowData._disabled = true
            tableRowData._highlight = true
            break
          }
        }
    }
  }
}

/**
 * table表格选中事件处理，选中某行
 * @param tableComponent table组件
 * @param selections 事件返回值
 * @param row 
 */
export const select = (tableComponent, selections, row) => {
  tableComponent.table.selections.push(row)
}

/**
 * table表格选中事件处理，取消选中某行
 * @param tableComponent table组件
 * @param selections 事件返回值
 * @param row 行数据
 * @param idProp 指明表格的id属性
 */
export const selectCancel = (tableComponent, selections, row, idProp) => {
  let id = 'id'
  if (idProp) {
    id = idProp
  }
  for (let selectionIndex in tableComponent.table.selections) {
    if (tableComponent.table.selections[selectionIndex][id] === row[id]) {
      tableComponent.table.selections.splice(selectionIndex, 1)
      break
    }
  }
}

/**
 * table表格选中事件处理，记录所有被选中的项
 * @param tableComponent table组件
 * @param selections 事件返回值
 * @param idProp 指明表格的id属性
 */
export const selectAll = (tableComponent, selections, idProp) => {
  let id = 'id'
  if (idProp) {
    id = idProp
  }
  for (let selectionIndex in selections) {
    let toPush = true
    let selectionData = selections[selectionIndex]
    if (selectionData._disabled) {
      toPush = false
      continue
    }
    for (let selectionIndex in tableComponent.table.selections) {
      if (tableComponent.table.selections[selectionIndex][id] === selectionData[id]) {
        toPush = false
        break
      }
    }
    if (toPush) {
      tableComponent.table.selections.push(selectionData)
    }
  }
}

/**
 * table表格选中事件处理，所有被取消的项
 * @param tableComponent table组件
 * @param selections 事件返回值
 * @param idProp 指明表格的id属性
 */
export const selectAllCancel = (tableComponent, selections, idProp) => {
  let id = 'id'
  if (idProp) {
    id = idProp
  }
  tableComponent.table.tableRows.forEach(selection => {
    for (let selectionIndex in tableComponent.table.selections) {
      if (tableComponent.table.selections[selectionIndex][id] === selection[id]) {
        tableComponent.table.selections.splice(selectionIndex, 1)
      }
    }
  })
}

/**
 * 单选
 * @param {*} tableComponent
 * @param {*} currentRow 
 * @param {*} oldCurrentRow 
 */
export const changeCurrent = (tableComponent, currentRow, oldCurrentRow) => {
  tableComponent.table.currentRow = currentRow
}

/**
 * table表格排序事件处理
 * @param tableComponent table组件
 * @param sortColumn 排序字段信息
 */
export const changeSort = (tableComponent, sortColumn) => {
  if (sortColumn.order === 'normal') {
    tableComponent.searchOpts.sortColumn = ''
    tableComponent.searchOpts.sortOrder = ''
  } else {
    tableComponent.searchOpts.sortColumn = sortColumn.key
    tableComponent.searchOpts.sortOrder = sortColumn.order
  }
  tableComponent.search()
}

/**
 * 分页组件页码改变事件处理
 * @param tableComponent table组件
 * @param pageNo 修改后的页码
 */
export const changePageNo = (tableComponent, pageNo) => {
  tableComponent.pager.pageNo = pageNo
  tableComponent.search()
}

/**
 * 分页组件每页大小改变事件处理
 * @param tableComponent table组件
 * @param pageSize 修改后的每页大小
 */
export const changePageSize = (tableComponent, pageSize) => {
  tableComponent.pager.pageSize = pageSize
  tableComponent.search()
}

/**
 * 根据路由名字打开一个新的tabl
 * @param {*} self this
 * @param {*} path 路由路径
 * @param {*} params 参数
 */
export const openTab = (self, path, params) => {
  self.$router.push({
    path: path,
    query: params
  })
}

/**
 * 导出json文件
 * @param self this
 */
export const exportJson = (self) => {
  doPostQsBlob(self.urls.exportUrl, {}, {}).then(response => {
    // fileDownload(JSON.stringify(response.data), self.exportFileName)
    fileDownload(response.data, self.exportFileName)
  }).catch(error => {
    console.log(error)
    self.$Message.error('导出失败，稍候再试')
  })
}

/**
 * 取指定多少天前或多少天后的时间
 * getDate(7)：7天后的时间
 * getDate(-7)：7天前的时间
 */
export const getDate = (date1, days) => {
  var time1 =
    date1.getFullYear() +
    '-' +
    (date1.getMonth() + 1) +
    '-' +
    date1.getDate()
  var date2 = new Date(date1)
  date2.setDate(date1.getDate() + days)
  var time2 =
    date2.getFullYear() +
    '-' +
    ((date2.getMonth() + 1) < 10 ? '0' + (date2.getMonth() + 1) : (date2.getMonth() + 1)) +
    '-' +
    (date2.getDate() < 10 ? '0' + date2.getDate() : date2.getDate())
  return time2
}

/**
 * 解析text文本到JSON对象
 * @param {*} data 
 */
export const parseJson = (data) => {
  return new Promise((resolve, reject) => {
    let json = JSON.parse(data)
    resolve(json)
  })
}

/**
 * 读取arrayBuffer数据到FileReader对象中，FileReader中存储字符串
 * @param {*} arrayBufferData 
 */
export const arrayBufferToReader = (arrayBufferData) => {
  let blob = new Blob([arrayBufferData])
  let reader = new FileReader()
  reader.readAsText(blob, 'utf-8')
  return reader
}

/**
 * 把arrayBuffer数据转化成指定类型的图片
 * @param {*} imageType 
 * @param {*} arrayBufferData 
 */
export const arrayBufferToImage = (imageType, arrayBufferData) => {
  return 'data:image/' + imageType + ';base64,' + btoa(
    new Uint8Array(arrayBufferData).reduce((data, byte) => data + String.fromCharCode(byte), '')
  )
}

/**
 * 获取信息信息，并存储到storage中
 */
export const getSysInfo = (self) => {
  doGet('/sys-config/any/pic-config', {}).then(res => {
    if (res.data.code !== ResponseStatus.OK) {
      self.$Message.error(res.data.message)
    } else {
      if (localStorage) {
        let picInfo = res.data.data
        let picInfoStr = JSON.stringify(picInfo)
        localStorage.setItem(SYS_INFO_KEY, picInfoStr)
        localStorage.setItem('favicon', picInfo.tabImg)
        if (picInfo.loginBackImg) {
          self.loginStyle = {
            'background-image': 'url(' + picInfo.loginBackImg + ')'
          }
        }
      }
    }
  }).catch(error => {
    console.log(error)
    self.$Message.error('获取系统信息失败')
  })
}

/**
 * 根据指定的多个数据字典的code获取多个数据字典项的值，并缓存到前端
 * @param {*} dictCodes 如 ['IS_ACTIVE', 'PAYMENT_TYPE']
 */
export const getDataDict = (dictCodes) => {
  let dataDictItems = {}
  let dictCodesWithNoItems = []
  return new Promise((resolve, reject) => {
    if (!dictCodes || dictCodes.length === 0) {
      resolve(dataDictItems)
      return
    }
    dictCodes.forEach(dictCode => {
      let dictItems = localStorage.getItem(dictCode)
      if (dictItems) {
        dataDictItems[dictCode] = JSON.parse(dictItems)
      } else {
        dictCodesWithNoItems.push(dictCode)
      }
    })
    if (dictCodesWithNoItems.length <= 0) {
      resolve(dataDictItems)
    } else {
      doPostJson('/data-dict-and-item/any/by-dict-codes', dictCodesWithNoItems, {}).then(response => {
        if (response.data.code === ResponseStatus.OK) {
          dictCodesWithNoItems.forEach(dictCode => {
            localStorage.setItem(dictCode, JSON.stringify(response.data.data[dictCode]))
            dataDictItems[dictCode] = response.data.data[dictCode]
          })
        }
        resolve(dataDictItems)
      }).catch(error => {
        reject(error)
      })
    }
  })
}

/**
 * 获取表格中数据字典项
 * @param {*} self 
 * @param {*} dictCode 从指定的数据字典中获取
 * @param {*} value 
 */
export const getDataDictItemDisplayValue = (self, dictCode, value) => {
  let dictItems = self.dataDictItems[dictCode]
  if (!dictItems) {
    return {
      displayValue: value
    }
  }
  if (value !== null && value !== undefined && value !== '') {
    for (let i = 0, len = dictItems.length; i < len; i++) {
      if (value === dictItems[i].value) {
        return dictItems[i]
      }
    }
  }
  return {
    displayValue: value
  }
}

/**
 * 从指定的数据字典中获取下拉菜单显示的数据，把默认值
 * @param {*} self 
 * @param {*} dictCode 指定的数据字典
 * @param {*} formProp select下拉框中的form对应的属性名
 * @param {*} dataProp 整个select下拉框的数据对应的data属性名
 */
export const getSelectDictItems = (self, dictCode, formProp, dataProp) => {
  let dictItems = self.dataDictItems[dictCode]
  if (dictItems && dictItems.length > 0) {
    self[dataProp] = dictItems
    let itemValue = dictItems[0].value
    if (itemValue === null || itemValue === undefined || itemValue === '') {
      // 如果数据项值是空的，则需要把显示的中文值赋值给value
      self[dataProp].forEach(item => {
        item.value = item.displayValue
      })
    }
    if (self.form) {
      // 只有添加和编辑下拉菜单需要有下拉默认值
      for (let i = 0, len = dictItems.length; i < len; i++) {
        let item = dictItems[i]
        if (item.isDefault === 1) {
          self.form[formProp] = item.value
          break
        }
      }
    }
  }
}

/**
 * 获取详情中数据字典项的显示值
 * @param {*} self 
 * @param {*} dictCode 
 * @param {*} formProp 
 */
export const getDetailDictItemDisplayValue = (self, dictCode, formProp) => {
  let dictItems = self.dataDictItems[dictCode]
  for (let i = 0, len = dictItems.length; i < len; i++) {
      if (self.form[formProp] === dictItems[i].value) {
        self.form[formProp] = dictItems[i].displayValue
        break
      }
  }
}

export const uuid = () => {
  let s = []
  let hexDigits = "0123456789abcdef"
  for (let i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = "4" // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-"
  let uuid = s.join("")
  return uuid
}
    